//
//  MineLoginViewController.swift
//  House
//
//  Created by 吕品 on 16/7/1.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

import UIKit
import MBProgressHUD
public let naviColor = UIColor.init(colorLiteralRed: 0.831, green: 0.149, blue: 0.102, alpha: 1.0)
class MineLoginViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
    var tableView = UITableView()
    var imageArr = [UIImage]()//图片数组
    var placeArr = [String]()//站位数组
    var naviBar = BaseTitleNavigationBar()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tabBarController?.tabBar.isHidden = true
        //navigationController?.navigationBar.isHidden = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        tabBarController?.tabBar.isHidden = false
        //navigationController!.navigationBar.isHidden = true
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        naviBar = BaseTitleNavigationBar.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: 64), withTitleStr: "登录")
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(back(tap:)))
        
        naviBar.leftView.addGestureRecognizer(tap)
        view.addSubview(naviBar)
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 64, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 64), style: .plain)
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.lightText
        tableView.register(ReuseImageViewAndTextFieldTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(ReuseImageViewAndTextFieldTableViewCell.self))
        imageArr = [UIImage.init(named: "MinePhoneNumber")!, UIImage.init(named: "MinePassword")!]
        placeArr = ["请输入手机号", "请输入密码"]
        //footer
        let footerView = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 150))
        tableView.tableFooterView = footerView
        tableView.backgroundColor = UIColor.groupTableViewBackground
        tableView.isScrollEnabled = false
        let loginButton = UIButton.init(type: .system)
        footerView.addSubview(loginButton)
        loginButton.backgroundColor = naviColor
        loginButton.tintColor = UIColor.white
        loginButton.addTarget(self, action:#selector(MineLoginViewController.login) , for: .touchUpInside)
        loginButton.setTitle("登录", for: UIControlState())
        loginButton.layer.masksToBounds = true
        loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        loginButton.layer.cornerRadius = 8

        let regButton = UIButton.init(type: .system)
        footerView.addSubview(regButton)
        regButton.backgroundColor = UIColor.clear
        regButton.tintColor = naviColor
        regButton.setTitle("立即注册", for: UIControlState())
        regButton.addTarget(self, action: #selector(MineLoginViewController.regNewMember(_:)), for: .touchUpInside)

        let forgetButton = UIButton.init(type: .system)
        footerView.addSubview(forgetButton)
        forgetButton.backgroundColor = UIColor.clear
        forgetButton.tintColor = UIColor.gray
        forgetButton.setTitle("忘记密码", for: UIControlState())
        forgetButton.addTarget(self, action: #selector(MineLoginViewController.regNewMember(_:)), for: .touchUpInside)
        let padding : CGFloat = 25
        let width = 80

        loginButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(padding)
            make.right.equalTo(-(padding + 10))
            make.left.equalTo(padding + 10);
            make.height.equalTo(60)
        }
        regButton.snp.makeConstraints { (make) in
            make.left.equalTo(loginButton)
            make.top.equalTo(loginButton.snp.bottom).offset(15)
            make.width.equalTo(width)
            make.height.equalTo(padding)
        }

        forgetButton.snp.makeConstraints { (make) in
            make.right.equalTo(loginButton)
            make.top.equalTo(loginButton.snp.bottom).offset(15)
            make.width.equalTo(width)
            make.height.equalTo(padding)
        }
        // Do any additional setup after loading the view.
    }
    func regNewMember(_ button: UIButton) -> Void {
        let regVC = MineRegViewController()
        regVC.title = button.titleLabel?.text
        self.navigationController!.pushViewController(regVC, animated: true)
    }
    func login() -> Void {//登录
        let phoneNum = (view.viewWithTag(1000) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!
        let password = (view.viewWithTag(1001) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.mode = .text
        if password == "" || phoneNum == "" {
            self.hide(withTitle: "用户名或者密码不能为空")
        } else {
            hud.label.text = "登录中"
            NetRequest.updateOrGetInformation(fromUrl: PHPHeader.manager().loginPHP, withParameters: ["tel": phoneNum, "pwd": password], success: { (task, responseObject1) in
                print(responseObject1)
                if responseObject1 is NSDictionary {
                    let responseObject = responseObject1 as! NSDictionary
                    switch ((responseObject["flg"]! as AnyObject).description)! as String {
                    case "1":
                        hud.label.text = "用户名不存在"
                        DispatchQueue.main.async(execute: {
                            hud.hide(animated: true, afterDelay: 1.0)
                        })
                        break
                    case "2":
                        let dic = responseObject["data"] as! NSDictionary

                        let uid = dic["userid"] as! String

                        let nickName = dic["nicheng"] as? String

                        //                        UserInfoManager.manager().storeUserInfo(uid, phoneNumber: phoneNum, loginStatus: true)
                        UserInfoManager.shared().initWithUserID(uid, phoneNumber: phoneNum, userName: nickName)
                        self.hide(withTitle: "登录成功")
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                            print(self.navigationController?.popViewController(animated: true))
                        })
                        break
                    case "3":
                            self.hide(withTitle: "密码错误")
                        break
                        case "4":
                            self.hide(withTitle: "您没有权限登录次版本")
                        break
                    default:
                        hud.label.text = "登录失败"
                        DispatchQueue.main.async(execute: {
                            hud.hide(animated: true, afterDelay: 1)
                        })
                        break
                    }
                }


                }, failure: { (task, error) in
                    print(error)
                    hud.mode = .text
                    hud.label.text = "登录失败,请稍后再试"
                    DispatchQueue.main.async(execute: {
                        hud.hide(animated: true, afterDelay: 1.0)
                    })
            })
        }

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return imageArr.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(ReuseImageViewAndTextFieldTableViewCell.self)) as! ReuseImageViewAndTextFieldTableViewCell
        cell.mixView.imageView.image = imageArr[(indexPath as NSIndexPath).row]
        cell.mixView.textField.placeholder = placeArr[(indexPath as NSIndexPath).row]
        cell.mixView.isShowButton = false
        cell.tag = tagManager + (indexPath as NSIndexPath).row
        cell.selectionStyle = .none
        if (indexPath as NSIndexPath).row == 1 {
            cell.mixView.textField.isSecureTextEntry = true
        }
        return cell

    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @objc func back(tap: UITapGestureRecognizer) -> Void {
        self.navigationController!.popViewController(animated: true)
    }

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
